package com.tendory.gpssim.service.jt808;

import android.util.Log;

import com.tendory.common.base.RxBus;
import com.tendory.jt808.msg.Message;
import com.tendory.jt808.msg.Packet;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MsgInHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf headerBodyBuf = (ByteBuf) msg;
        String orgMsg = ByteBufUtil.hexDump(headerBodyBuf);
        if (headerBodyBuf.readableBytes() <= 0) {
            return;
        }
//        headerBodyBuf.skipBytes(1);
        headerBodyBuf = doEscape4Receive(headerBodyBuf);
        byte[] raw = new byte[headerBodyBuf.readableBytes()];
//        System.arraycopy(buf, 0, raw, 0, len);
        headerBodyBuf.readBytes(raw);
        Packet packet = new Packet(raw);
//        Log.d(TAG, "readPackets: " + packet);
        Message msg1 = new Message.Builder(packet).build();
//        RxBus.getInstance().post(msg1);
        EventBus.getDefault().post(msg1);
//        processMessage(msg);
//        if (decodedMessage != null) {
//            ctx.fireChannelRead(decodedMessage);
//        }
    }
    private static ByteBuf doEscape4Receive(ByteBuf headerBodyBuf) {
        byte[] req = new byte[headerBodyBuf.readableBytes()];
        //1、复制内容到字节数组b
        headerBodyBuf.readBytes(req);
        try {
            //2.转义
            req = doEscape4Receive(req, 0, req.length);

            //3、创建缓冲区
            headerBodyBuf = Unpooled.buffer(8);

            //4、从字节数组写数据
            headerBodyBuf.writeBytes(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return headerBodyBuf;
    }

    public static ByteBuf doEscape4Send(ByteBuf bb) {
        byte[] req = new byte[bb.readableBytes()];
        //1、复制内容到字节数组b
        bb.readBytes(req);
        try {
            //2.转义
            req = doEscape4Send(req, 0, req.length);

            //3、创建缓冲区
            bb = Unpooled.buffer(8);

            //4、从字节数组写数据
            bb.writeBytes(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bb;
    }
    public static byte[] doEscape4Send(byte[] bs, int start, int end) throws Exception {
        if (start < 0 || end > bs.length) {
            throw new ArrayIndexOutOfBoundsException("doEscape4Send error : index out of bounds(start=" + start
                    + ",end=" + end + ",bytes HeaderLength=" + bs.length + ")");
        }
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            for (int i = 0; i < start; i++) {
                baos.write(bs[i]);
            }
            for (int i = start; i < end; i++) {
                if (bs[i] == 0x7e) {
                    baos.write(0x7d);
                    baos.write(0x02);
                } else if (bs[i] == 0x7d) {
                    baos.write(0x7d);
                    baos.write(0x01);
                } else {
                    baos.write(bs[i]);
                }
            }
            for (int i = end; i < bs.length; i++) {
                baos.write(bs[i]);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            throw e;
        } finally {
            if (baos != null) {
                baos.close();
                baos = null;
            }
        }
    }
    public static byte[] doEscape4Receive(byte[] bs, int start, int end) throws Exception {
        if (start < 0 || end > bs.length) {
            throw new ArrayIndexOutOfBoundsException("doEscape4Receive error : index out of bounds(start=" + start
                    + ",end=" + end + ",bytes HeaderLength=" + bs.length + ")");
        }
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            for (int i = 0; i < start; i++) {
                baos.write(bs[i]);
            }
            for (int i = start; i < end - 1; i++) {
                if (bs[i] == 0x7d && bs[i + 1] == 0x01) {
                    baos.write(0x7d);
                    i++;
                } else if (bs[i] == 0x7d && bs[i + 1] == 0x02) {
                    baos.write(0x7e);
                    i++;
                } else {
                    baos.write(bs[i]);
                }
            }
            for (int i = end - 1; i < bs.length; i++) {
                baos.write(bs[i]);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            throw e;
        } finally {
            if (baos != null) {
                baos.close();
                baos = null;
            }
        }
    }
}
